package com.pj.point;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
import com.pj.point.fragment.HomeFragment;
import com.pj.point.fragment.MyFragment;
import com.pj.point.fragment.PointFragment;
import com.pj.point.fragment.PrivateFragment;
import com.pj.point.litepal.CreateData;
import com.pj.point.litepal.DiaryJavaBean;

import org.litepal.LitePal;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private DrawerLayout drawer;
    private FrameLayout mainFragment;
    private BottomNavigationView mainNav;
    private LinearLayout leftNav;
    private Toolbar bar;


    private TextureMapView mapView = null;
    private BaiduMap baiduMap;
    private boolean isFirstLocate = true;
    private LocationClient mLocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initMap();
        initView();
        replace(new HomeFragment());
        bar.setNavigationOnClickListener(new View.OnClickListener() {
            @SuppressLint("WrongConstant")
            @Override
            public void onClick(View view) {
                if (drawer.isDrawerOpen(Gravity.START)) {
                    drawer.closeDrawer(Gravity.START);
                } else {
                    drawer.openDrawer(Gravity.START);
                }
            }
        });
        mainNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.home_nav_home: {
                        replace(new HomeFragment());
                        break;
                    }
                    case R.id.home_nav_private: {
                        replace(new PrivateFragment());
                        break;
                    }
                    case R.id.home_nav_point: {
                        replace(new PointFragment());
                        break;
                    }
                    case R.id.home_nav_myself: {
                        SharedPreferences data = getSharedPreferences("data", MODE_PRIVATE);
                        if (data.getBoolean("isLogin",false)) {
                            replace(new MyFragment());
                        }else {
                            startActivityForResult(new Intent(MainActivity.this,Login.class),9);
                        }
                        break;
                    }
                }
                return true;
            }
        });

    }

    private void initMap() {
        if (!getGpsStatus(getApplication()))
        {
            Snackbar.make(getWindow().getDecorView(),"定位服务并未打开",Snackbar.LENGTH_LONG)
                    .setAction("去开启......", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(intent);
                        }
                    }).show();
        }
        mLocationClient = new LocationClient(getApplicationContext());//创建Location实例并接受Context参数
        mLocationClient.registerLocationListener(new MyLocationListener());//注册定位监视器，接受位置信息时会回调到该监视器
        SDKInitializer.initialize(this.getApplicationContext());//初始化操作，传入Context
        setContentView(R.layout.activity_main);
        mapView = (TextureMapView) findViewById(R.id.map);
        baiduMap = mapView.getMap();
        baiduMap.setMyLocationEnabled(true);//显示当地位置
        mLocationClient.start();//开始定位，定位成功后会回调到监视器
        initLocation();
    }


    private void initView() {
        drawer = (DrawerLayout) findViewById(R.id.drawer);
        mainFragment = (FrameLayout) findViewById(R.id.main_fragment);
        mainNav = (BottomNavigationView) findViewById(R.id.main_nav);
        leftNav = (LinearLayout) findViewById(R.id.left_nav);
        bar = (Toolbar) findViewById(R.id.bar);
    }

    public void replace(Fragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.main_fragment, fragment);
        transaction.commit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1){
            switch (requestCode){
                case 1 :replace(new HomeFragment());
                break;
                case 2:{
                    replace(new MyFragment());
                    break;
                }
            }
        }
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setCoorType("bd09ll");//直接返回Bi0911坐标系，避免地图纠偏
        option.setScanSpan(5000);//每隔5000毫秒更新一次定位信息
        option.setLocationMode(LocationClientOption.LocationMode.Device_Sensors);//强制GPS
        option.setIsNeedAddress(true);//需要精确的信息
        mLocationClient.setLocOption(option);
    }


    public static boolean getGpsStatus(Context ctx) {
        //从系统服务中获取定位管理器
        LocationManager lm = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
        return lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation.getLocType() == bdLocation.TypeGpsLocation || bdLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
                navigateTo(bdLocation);
            }
            StringBuilder currentPostion = new StringBuilder();
            currentPostion.append("纬度：").append(bdLocation.getLatitude()).append("\n");//将经纬度信息转化为国家/省份/城市等信息
            currentPostion.append("经度：").append(bdLocation.getLongitude()).append("\n");
            currentPostion.append("国家：").append(bdLocation.getCountry()).append("\n");
            currentPostion.append("省：").append(bdLocation.getProvince()).append("\n");
            currentPostion.append("市：").append(bdLocation.getCity()).append("\n");
            currentPostion.append("区：").append(bdLocation.getDistrict()).append("\n");
            currentPostion.append("街道：").append(bdLocation.getStreet()).append("\n");
            if (bdLocation.getLocType() == bdLocation.TypeGpsLocation) {//判断定位的类型
                currentPostion.append("GPS");
            } else if (bdLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
                currentPostion.append("网络");
            } else {
                currentPostion.append("无");
            }
        }
    }

    private void navigateTo(BDLocation location) {//显示自己在地图上的位置
        if (isFirstLocate) {
            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());//存储经纬度到LatLng
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
            baiduMap.animateMapStatus(update);//显示我所在的区域
            update = MapStatusUpdateFactory.zoomTo(16f);//地图显示的缩放级别
            baiduMap.animateMapStatus(update);//传入到经纬度
            isFirstLocate = false;//防止多次调用
        }
        MyLocationData.Builder locationBuilder = new MyLocationData.Builder();//将经纬度信息存储到 Builder中
        locationBuilder.latitude(location.getLatitude());
        locationBuilder.longitude(location.getLongitude());
        MyLocationData locationData = locationBuilder.build();
        baiduMap.setMyLocationData(locationData);//将我的位置显示出来
    }

    @Override
    public void onResume() {//重写onResume
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {//重写onPause
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {//重写onDestroy
        super.onDestroy();
        mapView.onDestroy();
        mLocationClient.stop();
        baiduMap.setMyLocationEnabled(false);
    }

}